import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { CustomFlowSubmitService } from 'src/custom-flow-submit/custom-flow-submit.service';
import { CustomFlowService } from 'src/custom-flow/custom-flow.service';
import { CustomFlow } from 'src/custom-flow/entities/custom-flow.entity';
import Matter from 'src/matter/entities/matter.entity';
import { ResData, Status } from 'src/response/res-data.interface';
import { Repository } from 'typeorm';
import { CreateMatterSubmitDto } from './dto/create-matter-submit.dto';
import { UpdateMatterSubmitDto } from './dto/update-matter-submit.dto';
import { MatterSubmit } from './entities/matter-submit.entity';

@Injectable()
export class MatterSubmitService {
  constructor(@InjectRepository(MatterSubmit) private matterSubmitRepository: Repository<MatterSubmit>, private readonly customFlowService: CustomFlowService, private readonly customFlowSubmitService: CustomFlowSubmitService) { }

  async create(createMatterSubmitDto: CreateMatterSubmitDto) {
    let resdata: ResData;
    try {
      const result = await this.matterSubmitRepository.save(createMatterSubmitDto);
      const customFlow = await this.customFlowService.findOne((createMatterSubmitDto as any).customFlowId)
      const submitFlows = customFlow.content.customFlowNodes.map((node, index) => {
        return {
          customFlowNodeId: node.id,
          customFlowId: node.formId,
          matterSubmitId: result.id,
          sort: index
        }
      })
      this.customFlowSubmitService.create(submitFlows)
      resdata = {
        code: Status.SUCCESS,
        msg: '保存成功',
        content: result
      };
      return resdata;
    } catch (e) {
      resdata = {
        code: Status.ERROR,
        msg: e,
      };
      return resdata;
    }
  }

  async findAll(querys) {
    let resdata: ResData;
    try {
      const { startTime, endTime, matterName } = querys;
      let sql = this.matterSubmitRepository.createQueryBuilder("matterSubmit");
      sql.leftJoinAndSelect('matterSubmit.matter', "matter")
      if (startTime) {
        sql.andWhere('matterSubmit.createdDate between :startTime and :endTime', { startTime, endTime })
      }
      if (matterName) {
        sql.andWhere('matter.matterName like :matterName', { matterName: `%${matterName}%` })
      }
      const result = await sql.skip(querys.skip).take(querys.take).orderBy("matterSubmit.updatedDate", "DESC").getManyAndCount()

      const [list, total] = result
      resdata = {
        code: Status.SUCCESS,
        msg: '查询成功',
        content: {
          result: list,
          total
        }
      };
      return resdata;
    } catch (e) {
      resdata = {
        code: Status.ERROR,
        msg: e,
      };
      return resdata;
    }
  }

  async findOne(id: string) {
    let resdata: ResData;
    try {
      let result = await this.matterSubmitRepository.findOne(id, { relations: ["matter", "matter.dept"] });
      const completeFlow = await this.customFlowSubmitService.findCompleteFlow(id);
      const curFlow = await this.customFlowSubmitService.findCurFlow(id);
      resdata = {
        code: Status.SUCCESS,
        msg: '查询成功',
        content: { result, curFlow, completeFlow }
      };
      return resdata;
    } catch (e) {
      resdata = {
        code: Status.ERROR,
        msg: e,
      };
      return resdata;
    }
  }

  async update(id: string, updateMatterSubmitDto: UpdateMatterSubmitDto) {
    let resdata: ResData;
    try {
      const result = await this.matterSubmitRepository.update(id, updateMatterSubmitDto);
      resdata = {
        code: Status.SUCCESS,
        msg: '更新成功',
        content: result
      };
      return resdata;
    } catch (e) {
      resdata = {
        code: Status.ERROR,
        msg: e,
      };
      return resdata;
    }
  }

  async remove(id: string) {
    let resdata: ResData;
    try {
      const result = await this.matterSubmitRepository.delete(id);
      resdata = {
        code: Status.SUCCESS,
        msg: '删除成功',
        content: result
      };
      return resdata;
    } catch (e) {
      resdata = {
        code: Status.ERROR,
        msg: e,
      };
      return resdata;
    }
  }

  async submit(body) {
    let resdata: ResData;
    const { matterSubmitId, curFlowId, customFormSubmitId } = body;
    try {
      await this.customFlowSubmitService.update(curFlowId, { customFormSubmitId })
      const curFlow = await this.customFlowSubmitService.findCurFlow(matterSubmitId)
      if (curFlow) {
        this.matterSubmitRepository.update(matterSubmitId, { status: '1' })
      } else {
        this.matterSubmitRepository.update(matterSubmitId, { status: '2' })
      }
      resdata = {
        code: Status.SUCCESS,
        msg: '提交成功'
      };
      return resdata;
    } catch (e) {
      resdata = {
        code: Status.ERROR,
        msg: e,
      };
      return resdata;
    }
  }
}
